package com.ry.common.utils;

import cn.hutool.core.util.HashUtil;
import com.ry.request.InventoryRequest;
import com.ry.request.InventoryRequestQueue;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.util.concurrent.ArrayBlockingQueue;

/**
 * 请求分发
 */
@Slf4j
@Component
public class RequestDistributionUtil {

    /**
     * 处理库存请求
     * @param inventoryRequest
     */
    public void handleInventoryRequest(InventoryRequest inventoryRequest){

        InventoryRequestQueue inventoryRequestQueue = InventoryRequestQueue.getInstance();

        Long productId = inventoryRequest.getProductId();
        // 取得hash值
        int hash = HashUtil.oneByOneHash(productId.toString());
        // 取得内存队列下标
        int index = inventoryRequestQueue.size() & hash;

        log.info("===日志===：路由内存队列，商品id={},内存队列索引={}",productId,index);

        ArrayBlockingQueue<InventoryRequest> queue = inventoryRequestQueue.get(index);

        try {
            // 将库存请求分发 存入对应内存队列
            queue.put(inventoryRequest);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

}
